package com.ttdevs.util.view;

import java.util.Calendar;

import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.ttdevs.R;

public class NumberShowView extends TableLayout {

	private static final int DAYCOUNT = 5;
	private static final String[] WEEKDAY = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };

	private TableRow.LayoutParams lpTableRowMacth ;
	private TableRow.LayoutParams lpTableRowWrap ;

	public NumberShowView(Context context) {
		this(context, null);
	}

	public NumberShowView(Context context, AttributeSet attrs) {
		super(context, attrs);

		initView();
	}

	private void initView() {
		lpTableRowMacth = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
				TableRow.LayoutParams.WRAP_CONTENT);
		lpTableRowWrap = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
				TableRow.LayoutParams.WRAP_CONTENT);
		
		lpTableRowMacth.weight = 1;
		
		setShrinkAllColumns(true);
		setBackgroundResource(R.drawable.bg_number_show);

		// addView(createTitle(), lpTableRow);
		// addView(createBody("上午"), lpTableRow);
		// addView(createBody("下午"), lpTableRow);
		// addView(createBody("夜晚"), lpTableRow);

		addView(createTitle());
		addView(createBody("上午"));
		addView(createBody("下午"));
		addView(createBody("夜晚"));
	}

	private TableRow createTitle() {
		TableRow tr = new TableRow(getContext());
		tr.setGravity(Gravity.CENTER);
		
		TextView tvNull = new TextView(getContext());
		tr.addView(tvNull);
		
		for (int i = 0; i < DAYCOUNT; i++) {
			TextView tv = new TextView(getContext());
			tv.setGravity(Gravity.CENTER);
			tv.setText(getTitleDay(i));
			
			tr.addView(tv);
		}
		return tr;
	}

	private TableRow createBody(String tag) {
		TableRow tr = new TableRow(getContext());
		tr.setGravity(Gravity.CENTER);
		
		TextView tv = new TextView(getContext());
		tv.setText(tag);
		tv.setGravity(Gravity.CENTER);
		
		tr.addView(tv);
		
		for (int i = 0; i < DAYCOUNT; i++) {
			Button btn = new Button(getContext());
			btn.setText(String.valueOf((int)(Math.random()*10)));
			btn.setGravity(Gravity.CENTER);

			// tr.addView(btn);
			tr.addView(btn);
		}
		return tr;
	}

	private String getTitleDay(int index) {
		StringBuilder sb = new StringBuilder();
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, index); // 日期加index天
		int month = cal.get(Calendar.MONTH) + 1; // 月份要加1
		int day = cal.get(Calendar.DATE);
		sb.append(String.format("%02d", month) + "-" + String.format("%02d", day));
		sb.append("\n");
		int week = cal.get(Calendar.DAY_OF_WEEK);
		sb.append(WEEKDAY[week - 1]);
		return sb.toString();
	}
}
